using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using ListItem = System.Web.UI.WebControls.ListItem;
using System.Threading;
using System.Globalization;
using System.Configuration;

namespace TfsProxyMonitor
{
    public partial class MainForm : Form
    {

        #region Private

        //const double TIMER_INTERVAL = 5 * 60 * 1000;  //5 minutes
        const double TIMER_INTERVAL = 5 * 1000;
        private System.Timers.Timer timer = null;


        private ICredentials credentital = null;
        private string proxyUrl = string.Empty;
        private TfsProxyStatistics.ProxyStatistics proxyStatic = null;
        private TfsProxyStatistics.ProxyStatisticsInfo[] proxyInfo = null;

        private string userName = string.Empty;
        private string password = string.Empty;
        private string domain = string.Empty;

        #endregion



        internal MainForm()
        {
            InitializeComponent();

            InitConfig();
        }

        private void InitConfig()
        {
            timer = new System.Timers.Timer(TIMER_INTERVAL);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            //timer.Start();

            proxyUrl = ConfigurationManager.AppSettings["TfsProxyUrl"];
            proxyStatic = new TfsProxyMonitor.TfsProxyStatistics.ProxyStatistics(proxyUrl);

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UserName"]) &&
                !string.IsNullOrEmpty(ConfigurationManager.AppSettings["Password"]))
            {
                userName = ConfigurationManager.AppSettings["UserName"];
                password = ConfigurationManager.AppSettings["Password"];
                domain = string.IsNullOrEmpty(ConfigurationManager.AppSettings["Domain"]) ? "" : ConfigurationManager.AppSettings["Domain"];
                credentital = new NetworkCredential(userName, password, domain);
                proxyStatic.Credentials = credentital;
            }
            else
            {
                proxyStatic.UseDefaultCredentials = true;
            }
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //lblStatus.Text = string.Format("Last updated at {0}", proxyInfo.Length.ToString(), DateTime.Now.ToLocalTime().ToString());
            ConnectToTfsProxy();
        }
        
        private void MainForm_Load(object sender, EventArgs e)
        {
            ConnectToTfsProxy();
        }
        
        private void btnConnect_Click(object sender, EventArgs e)
        {
            ConnectToTfsProxy();
        }
        
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if ((proxyInfo == null) || (proxyInfo.Length == 0))
            {
                ConnectToTfsProxy();
            }
        }
        
        private void cmbProxyArray_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListItem item = (ListItem)cmbProxyArray.SelectedItem;
            if (item == null)
            {
                return;
            }

            if ((proxyInfo == null) || (proxyInfo.Length == 0))
            {
                ConnectToTfsProxy();
            }

            foreach (TfsProxyStatistics.ProxyStatisticsInfo info in proxyInfo)
            {
                if (info.ServerId == item.Value)
                {
                    txtServerId.Text = info.ServerId.ToUpper();
                    txtCurrentCacheSize.Text = FormatFileSize((decimal)info.CurrentCacheSize);
                    txtNoOfRequest.Text = info.NoOfRequests.ToString();
                    txtOverallCacheHit.Text = info.OverallCacheHits.ToString();
                    txtNoOfFilesInCache.Text = info.NoOfFilesInCache.ToString();
                    txtOverallCacheMiss.Text = info.OverallCacheMisses.ToString();
                    txtCacheHitPercent.Text = info.CacheHitsPercentage.ToString();
                    txtCacheMissPercent.Text = info.CacheMissPercentage.ToString();
                    break;
                }
            }
        }




        #region "Connect to Proxy WS routine"

        private delegate void ProxyConnectComplete(TfsProxyStatistics.ProxyStatisticsInfo[] proxyInfo);

        private void ConnectToTfsProxy()
        {
            lblStatus.Text = "Connecting to Tfs Proxy Server...";

            Thread connectThread = new Thread(new ThreadStart(StartConnectTfsProxy));
            connectThread.Start();
        }
        
        private void StartConnectTfsProxy()
        {
            try
            {
                proxyInfo = proxyStatic.QueryProxyStatistics();
                if (proxyInfo == null)
                {
                    MessageBox.Show("TPM001 error: Error while connect to server.");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            this.Invoke(new ProxyConnectComplete(ConnectToTfsProxyComplete), new object[] { proxyInfo });
        }

        private void ConnectToTfsProxyComplete(TfsProxyStatistics.ProxyStatisticsInfo[] proxyInfo)
        {
            lblStatus.Text = string.Format("Proxy connected, {0} server(s) currently in Proxy Array. Last updated at {1}", proxyInfo.Length.ToString(), DateTime.Now.ToLocalTime().ToString());

            cmbProxyArray.Items.Clear();
            foreach (TfsProxyStatistics.ProxyStatisticsInfo info in proxyInfo)
            {
                ListItem item = new ListItem();
                item.Text = info.ServerUrl;
                item.Value = info.ServerId;
                cmbProxyArray.Items.Add(item);
            }

            if (cmbProxyArray.Items.Count >= 1)
            {
                cmbProxyArray.SelectedIndex = 0;
            }
        }

        #endregion




        private string FormatFileSize(decimal size)
        {
            decimal tmp = 0.0M;
            string rtn = string.Empty;
            rtn = "{0} {1}";
            if (size >= 1024 * 1024 * 1024)
            {
                tmp = size / (1024 * 1024 * 1024);
                rtn = string.Format(rtn, tmp.ToString("0.00", CultureInfo.CurrentCulture), "GB");
            }
            else if (size >= 1024 * 1024)
            {
                tmp = size / (1024 * 1024);
                rtn = string.Format(rtn, tmp.ToString("0.00", CultureInfo.CurrentCulture), "MB");
            }
            else if (size >= 1024) // KB
            {
                tmp = size / 1024;
                rtn = string.Format(rtn, tmp.ToString(), "KB");
            }

            rtn = (size == 0) ? "..." : string.Format(rtn, size, "bytes");

            return rtn;
        }

      


    }
}